package com.ssi.mrms.security;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.ssi.mrms.model.Role;
import com.ssi.mrms.model.User;
import com.ssi.mrms.service.UserService;

public class UserDetailService implements UserDetailsService {

	private final static Logger logger = Logger.getLogger(UserDetailService.class);

	@Autowired
	UserService userService = null;

	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		logger.info("loadUserByUsername : " + username);
		List<WebRole> roles = new ArrayList<WebRole>();
		User user = null;
		try {
			user = userService.findLoginUsername(username);
			if (user == null) {
				throw new UsernameNotFoundException("Username " + username + " not found.");
			}
			logger.info("Username : " + username);
//			logger.info("Role : " + Arrays.toString(user.getRoles().toArray(new String[0])));
			for (Role role : user.getRoles()) {
				roles.add(new WebRole(role.getRoleName()));
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		
		return new WebUserDetails(username, user.getPassword(), roles);

	}


}
